// miniprogram/pages/campus-comment/campus-comment.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

const db = wx.cloud.database()
let likeDisabled = false
let itemId = ''
let lastCommentNumber = 0
const batchSize = 20
var req = require("../../utils/action.js")
var utils = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    item: {},
    commentList: [],
    showPopup: false,
    content: '',
    ifAnonymous: false,
    ifValid: false,
    ifLike: false,
    ifHimself: false,
    repplyText:'在这写评论',
    repplyId:-1,
    repplyOpenid:-1,
    commentImageList:[],
    submitImagePath:[],
    publishTitle:"本名发布",
    controlOpenStatus:true
  },  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log(options)
    let userInfo = await getApp().globalData.userInfo
    console.log(userInfo)
    this.setData({userInfo:userInfo})
    if(options) {
      itemId = options.itemId
      this.findInvitationInfo()
      this.getCommentList()
    }
  },
  getCommentList(){
    let _url = req.actions.ym+ "zentoComment/getCommentList",data={invitationId:itemId},that=this, userInfo = getApp().globalData.userInfo
    this.setData({loading:true})
    utils.getAction(data,_url,function(res){
      console.log("getCommentList===>"+JSON.stringify(res))
      that.setData({commentList:res.data.result,loading:false})
    })
  },
  afterImgRead(event) {
    let that = this
    console.log(event)
    that.setData({
      commentImageList: that.data.commentImageList.concat(event.detail.file)
    })
  },
  onImgDelete(event) {
    console.log(event.detail.index)
    this.data.commentImageList.splice(event.detail.index, 1)
    this.setData({
      commentImageList: this.data.commentImageList
    })
    console.log( this.data.commentImageList)
  },
  onChangeAnonymous({ detail }) {
    console.log(detail)
    if(detail){
      this.setData({ ifAnonymous: !this.data.ifAnonymous,publishTitle:'本名发布' })
    }else{
      this.setData({ ifAnonymous: !this.data.ifAnonymous,publishTitle:'随机名称发布' })
    }
  },
  async _getItemDetail(ifItem=false, ifOnlyComment=false, start=0) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    likeDisabled = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      commentList: [],
    }, async ()=>{
      this.findInvitationInfo()
      this.getCommentList()
      wx.stopPullDownRefresh()
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '这个很有趣，一起看看吧',
      path: `/pages/campus-comment/campus-comment?itemId=${itemId}`,
    }
  },
  findInvitationInfo(){
    let that = this, _url = req.actions.ym+ "invitation/findInvitationInfo"
    utils.getAction({invitationId:itemId,customerId:getApp().globalData.userInfo.id},_url,function(res){
      console.log("findInvitationInfo===>"+JSON.stringify(res))
      if(res.data.code == 200){
        let item = res.data.result.content
        item.favor = res.data.result.favor
        item.like = res.data.result.like
        that.setData({item: item})
        //console.log(item)
      }else{
        Dialog.alert({
          message: res.data.message
        }).then(() => { //点击确认按钮后的调用
          wx.navigateBack({delta: -1})
        })
        .catch(() => { //点击取消按钮后的调用
          wx.navigateBack({delta: -1})
        })
      }
      
    })
  },
  onLongPress(event) {
    console.log(event)
    if(this.data.userInfo.openid != event.currentTarget.dataset.openid) {
      Dialog.confirm({
        title: '确认要举报此帖吗',
      }).then(() => {
        let _url = req.actions.ym+ "invitation/reportInvitation",data={invitation_id:itemId,customer_id:this.data.userInfo.id},that=this
        console.log(data)
        utils.myResquest(data,_url,function(res){
          console.log("reportInvitation===>"+JSON.stringify(res))
          wx.showToast({
            title: '举报成功',
            icon: 'none'
          })
        })
      }).catch((err)=>{})
    }
  },
  callCommentPop(e){
    console.log("callCommentPop",e)
    if (!this.data.userInfo.myNickName) {
      wx.showToast({
        title: "请先去[我的->个人信息]界面完成身份验证~",
        icon: 'none'
      })
    } else if (!(this.data.userInfo.ifValid == 'Y')) {
      wx.showToast({
        title: "请等待身份验证通过~",
        icon: 'none'
      })
    } else {
      this.setData({
        showPopup: true,
        repplyText:'回复'+e.detail.nickName+":",
        repplyId:e.detail.commentId,
        toCustomerId:e.detail.toCustomerId,
        toNickName:e.detail.nickName
      })
    }
  },
  onLongPressComment(event) {
    console.log("onLongPressComment:"+JSON.stringify(event.currentTarget.dataset))
    let that = this
    if(userInfo.openid == event.currentTarget.dataset.openid) {
      Dialog.confirm({
        title: '确认要删除此评论吗',
      }).then(() => {
        let _url = req.actions.ym+ "invitation/deleteComment",data={commentId:event.currentTarget.dataset.id},that=this
        utils.myResquest(data,_url,function(res){
          console.log("onLongPressComment===>"+JSON.stringify(res))
          that.getCommentList()
          wx.showToast({
            title: '已删除~',
            icon: 'none'
          })
        })
      }).catch((err)=>{})
    } else {
      Dialog.confirm({
        title: '确认要举报此评论吗',
      }).then(() => {
        let _url = req.actions.ym+ "invitation/reportComment",data={comment_id:event.currentTarget.dataset.id,customer_id:userInfo.id},that=this
        utils.myResquest(data,_url,function(res){
          console.log("reportComment===>"+JSON.stringify(res))
          if(res.data.code == 200){
            wx.showToast({
              title: '举报成功~',
              icon: 'none'
            })
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        })
      }).catch((err)=>{})
    }
  },
  onClickComment() {
    if (!this.data.userInfo.myNickName) {
      wx.showToast({
        title: "请先去[我的->个人信息]界面完成身份验证~",
        icon: 'none'
      })
    } else if (!(this.data.userInfo.ifValid == 'Y')) {
      wx.showToast({
        title: "请等待身份验证通过~",
        icon: 'none'
      })
    } else {
      this.setData({
        showPopup: true,
        if_anonymous: this.data.userInfo.ifAnonymous
      })
    }
  },
  onCloseComment() {
    console.log("onCloseComment")
    this.setData({
      showPopup: false,
      repplyText:'在这写评论',
      repplyId:-1,
      if_anonymous:0,
      repplyOpenid:-1
    })
  },
  
  onSendComment(){
    let that = this;
    wx.getSetting({
      withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
      success: function(res){
        wx.requestSubscribeMessage({   // 调起消息订阅界面
          tmplIds: ['0NAN_O3MgKXxCwOdxMeLfrJV96DaSuv-Z53Sp0hgGIQ'],
          success (res) { 
            console.log('订阅消息 成功 ');
            console.log(res);
            that.onSendComment2("1")
          },
          fail (er){
            console.log("订阅消息 失败 ");
            console.log(er);
            that.onSendComment2("0")
          }
        })  
      },
      fail: function(error){
        console.log(error);
      },
    })
  },
  async onSendComment2(subscribeMegStatus) {
    let content = this.data.content,that=this
    if(this.data.item.overStatus == '1'){
      wx.showToast({
        title: '此贴已结束，不能再评论了哦~',
        icon: 'none'
      })
      return
    }
    if(content.trim() == '' && this.data.commentImageList.length <= 0 ) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '评论中',
      mask: true
    })
    let promiseArr = [],ifAnonymous = this.data.ifAnonymous ? 1 : 0
    const commentImageList = this.data.commentImageList
    console.log("commentImageList",commentImageList)
    let newComment = {
      invitationId:itemId,
      content,
      nickName:  this.data.item.randomNickName || this.data.item.nickName,
      avatarUrl: this.data.item.avatarUrl,
      reportNum: 0,
      customerId:this.data.userInfo.id,
      authorCustomerId:this.data.item.customerId,
      pid:this.data.repplyId,
      toCustomerId:this.data.toCustomerId,
      toNickName:this.data.toNickName,
      ifAnonymous:ifAnonymous
    }
    console.log("newComment",newComment)
    if(commentImageList && commentImageList.length > 0){
      for (let i = 0, len = commentImageList.length; i < len; i++) {
        let p = new Promise((resolve, reject) => {
          let item = commentImageList[i].url
          utils.upload(req.actions.ym+ "file/uploadPicture",item,'comment_img',1,function(res){
            console.log("res",res)
            if(res == 'fail'){
              wx.showToast({
                title: '发布失败，请重试',
                icon: 'error'
              })
              reject()
            }else{
              that.data.submitImagePath = that.data.submitImagePath.concat(res)
              resolve()
            }
          })
        })
        promiseArr.push(p)
      }
      Promise.all(promiseArr).then((res) => {
        console.log("submitImagePath", that.data.submitImagePath)
        newComment.imageList=(that.data.submitImagePath && that.data.submitImagePath.length > 0 ? JSON.stringify(that.data.submitImagePath) : null)
        console.log("newComment:"+JSON.stringify(newComment))
        that.sendComment(newComment)
      })
    }else{
      console.log("newComment:"+JSON.stringify(newComment))
      that.sendComment(newComment)
    }
      
    //console.log("this.data.ifAnonymous:"+this.data.ifAnonymous)
    
  },
  sendComment(newComment){
    let that=this,_url = req.actions.ym+ "zentoComment/sendComment"
    utils.myResquest(newComment,_url,function(res){
      //console.log("sendComment===>"+JSON.stringify(res))
      that.getCommentList()
      wx.hideLoading()
      wx.showToast({
        title: '评论成功~',
        icon: 'none'
      })
      that.setData({
        showPopup: false,
        content:"",
        commentImageList:[],
        submitImagePath:[],
        repplyText:'',
        repplyId:-1,
        toCustomerId:undefined,
        toNickName:'',
      })
    })
  },
  onClickFavor(){
    let _url = "",status = 0,that=this
    this.data.item.favor ? _url = req.actions.ym+ "zentoFavorite/operateFavorite" : _url = req.actions.ym+ "zentoFavorite/operateFavorite"
    this.data.item.favor ? status = 0 : status = 1
    utils.myResquest({invitationId:itemId,customerId:this.data.userInfo.id,status:status},_url,function(res){
      wx.hideLoading()
      if(res.data.success){
        wx.showToast({
          title: that.data.item.favor?'取消收藏成功~':'收藏成功~',
          icon: 'none'
        })
      }
      that.setData({"item.favor":!that.data.item.favor})
    })
    
  },
  onChangeComment(event) {
    this.setData({
      if_anonymous: event.detail
    })
  },
  onClickLike() {
    /*if(!likeDisabled) {
      likeDisabled = true
      
    }*/
    let _url = req.actions.ym+ "invitation/addLikeNum",that=this
    utils.myResquest({invitation_id:itemId,customer_id:this.data.userInfo.id},_url,function(res){
      //console.log("sendComment===>"+JSON.stringify(res))
      wx.hideLoading()
      if(res.data.code == '200'){
        wx.showToast({
          title: '点赞成功~',
          icon: 'none'
        })
        let likeNum = that.data.item.like_num ? that.data.item.like_num : 0
        if( that.data.item.like){
          likeNum = likeNum - 1
        }else{
          likeNum = likeNum + 1
        }
        that.setData({"item.like_num":likeNum,"item.like":!that.data.item.like})
        // likeDisabled = !likeDisabled
      }/*else if(res.data.code == '201'){
        likeDisabled = !likeDisabled
      }*/
    })
  },
  onPressOver() {
    Dialog.confirm({
      title: '确认要结束此贴子吗',
    }).then(() => {
      let _url = req.actions.ym+ "invitation/overInvitation"
      utils.myResquest({invitationId:itemId},_url,function(res){
        //console.log("sendComment===>"+JSON.stringify(res))
        wx.hideLoading()
        if(res.data.code == '200'){
          if(res.data.content){
            wx.showToast({
              title: '已结束~',
              icon: 'none'
            })
          }
        }
      })
    }).catch((err)=>{})
  },
})